"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 防篡改
Case Name   : 创建auditadmin用户、数据库对象对系统表权限验证
Create At   : 2022/3/14
Owner       : @daiguatutu
Description :
    1.设置参数并重启数据库enableseparationofduty=on
    2.创建auditadmin用户,数据库
    3.auditadmin用户登录,开启事务,增删改查系统表中的记录,回滚
    4.清理环境
Expect      :
    1.成功
    2.成功
    3.查询成功,增删改系统表失败
    4.清理环境成功
History     :
"""

import os
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import macro


class Security(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.common = Common()
        self.u_name = 'u_security_combineprivilege_0003'
        self.db_name = 'db_security_combineprivilege_0003'
        self.default_value1 = self.common.show_param('enableSeparationOfDuty')

    def test_security(self):
        text = '-----step1：设置参数并重启数据库enableSeparationOfDuty=on; ' \
               'expect:成功-----'
        self.log.info(text)
        mod_msg = self.pri_sh.execute_gsguc('set',
                                            self.constant.GSGUC_SUCCESS_MSG,
                                            'enableSeparationOfDuty=on')
        self.assertTrue(mod_msg, '执行失败:' + text)
        result = self.pri_sh.restart_db_cluster()
        self.assertTrue(result, '执行失败' + text)

        text = '-----step2：创建auditadmin用户和数据库 expect:成功-----'
        self.log.info(text)
        create_cmd = f"drop user if exists {self.u_name} cascade; " \
            f"create user {self.u_name} auditadmin password " \
            f"'{macro.COMMON_PASSWD}';" \
            f"drop database if exists {self.db_name};" \
            f"create database {self.db_name};"
        msg = self.pri_sh.execut_db_sql(create_cmd)
        self.log.info(msg)
        self.assertIn(self.constant.DROP_ROLE_SUCCESS_MSG, msg,
                      '执行失败:' + text)
        self.assertIn(self.constant.CREATE_ROLE_SUCCESS_MSG, msg,
                      '执行失败:' + text)
        self.assertIn(self.constant.DROP_DATABASE_SUCCESS, msg,
                      '执行失败:' + text)
        self.assertIn(self.constant.CREATE_DATABASE_SUCCESS, msg,
                      '执行失败:' + text)

        text = '-----step3：auditadmin用户登录,增删改查系统表中的记录; ' \
               'expect:查询成功,增删改系统表失败-----'
        self.log.info(text)
        insert_sql = f"insert into pg_database(datname,datdba,encoding," \
            f"datcollate, datctype,datistemplate,datallowconn,datconnlimit," \
            f"datlastsysoid,dattablespace)values (" \
            f"'db_priv_function_sys_table_001_tmp', 10,7,'en_us:utf-8' ," \
            f"'en_us:utf-8' ,'t' ,'t', -1, 13371,1663);"
        delect_sql = f"delete from pg_database " \
            f"where datname='{self.db_name}';"
        updata_sql = f"update pg_database set datname='{self.db_name}_new'" \
            f" where datname='{self.db_name}';"
        select_sql = f"select * from pg_database " \
            f"where datname='{self.db_name}';"
        connect = f'-U {self.u_name} -W {macro.COMMON_PASSWD}'
        sqls = [insert_sql, delect_sql, updata_sql, select_sql]
        for sql in sqls:
            sql_cmd = f"start transaction;" \
                f"{sql}" \
                f"rollback;"
            msg = self.pri_sh.execut_db_sql(sql_cmd, sql_type=connect)
            self.log.info(msg)
            self.assertIn(self.constant.START_TRANSACTION_SUCCESS_MSG, msg,
                          '执行失败:' + text)
            self.assertIn(self.constant.ROLLBACK_MSG, msg, '执行失败:' + text)
            if 'select' in sql:
                self.assertIn('1 row', msg, '执行失败:' + text)
                self.assertIn(self.db_name, msg, '执行失败:' + text)
            else:
                self.assertIn('permission denied for relation pg_database',
                              msg, '执行失败:' + text)

    def tearDown(self):
        self.log.info('-----step4：清理环境-----')
        text1 = '-----删除用户 expect:成功-----'
        self.log.info(text1)
        drop_cmd = f"drop user if exists {self.u_name} cascade;" \
            f"drop database if exists {self.db_name};"
        drop_msg = self.pri_sh.execut_db_sql(drop_cmd)
        self.log.info(drop_msg)

        text2 = '-----修改参数enableSeparationOfDuty为初始值 expect:成功-----'
        self.log.info(text2)
        mod_msg1 = self.pri_sh.execute_gsguc('set',
                                             self.constant.GSGUC_SUCCESS_MSG,
                                             f'enableSeparationOfDuty='
                                             f'{self.default_value1}')
        restart_res = self.pri_sh.restart_db_cluster()

        self.log.info('-----断言tearDown执行成功-----')
        self.assertIn(self.constant.DROP_ROLE_SUCCESS_MSG, drop_msg,
                      '执行失败:' + text1)
        self.assertIn(self.constant.DROP_DATABASE_SUCCESS, drop_msg,
                      '执行失败:' + text1)
        self.assertTrue(mod_msg1, '执行失败:' + text2)
        self.assertTrue(restart_res, '执行失败:' + text2)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
